package gappengko;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Handles request in either JSON or JSON/P */
public class ContentNegotiationUtils {

  public static void processRequest(HttpServletRequest req, HttpServletResponse resp, String json) throws Exception {

    // do we have a callback?
    // if yes it is JSON/P
    // we may also configure this with an "Accept: text/javascript" HTTP header field
    String callback = req.getParameter(Constants.CALLBACK);
    if (callback!=null || "text/javascript".equals(req.getHeader("Accept"))) {
      resp.setContentType("text/javascript");
      resp.getWriter().write(callback+"("+json+");\n");      
      return;
    }
    
    // otherwise, by default, it is pure JSON
    resp.setContentType("application/json");
    resp.getWriter().write(json);    
  }
  
}
